<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket-QiuQiu</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    .map {
        width: 19200px;
        height: 10800px;
        background-color: #000;
    }
</style>

<body>
<div class="map">
    <input type="text" id="x"><br>
    <input type="text" id="y"><br>
    <input type="text" id="name"><br>
    <button onclick="init()">初始化连接</button>
    <button onclick="sendPosition()">发送坐标</button>
<!--    释放技能-->
    <button onclick="sendSkill('skill1')" >释放技能</button>
    <button onclick="sendSkill('skill2')" >释放技能</button>
</div>
</body>
<!--导包 ScokJS库-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.4.0/sockjs.min.js"></script>
<!--导包 StompJS库-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>

<script>
    // 建立连接,对应下面的端点
    // @Override
    // public void registerStompEndpoints(StompEndpointRegistry registry) {
    //     //註冊/ws端點
    //     registry.addEndpoint("/ws").withSockJS();
    // }
    let socket;
    //创Stomp客户端实例
    let client;

    function init() {
        socket = new SockJS('http://192.168.182.221/ws');
        client = Stomp.over(socket);

        // 连接并订阅消息
        client.connect({}, function (frame) {
            //订阅消息
            client.subscribe("/game/position", function (message) {
                //接收消息
                let json = JSON.parse(message.body);
                //处理消息
                console.log(json);
            });

            client.subscribe("/game/skill", function (message) {
                //接收消息
                let json = JSON.parse(message.body);
                //处理消息
                console.log(json);
            });
        });
    };

    //发送坐标逻辑
    function sendPosition() {
        let x = document.getElementById("x").value;
        let y = document.getElementById("y").value;
        let name = document.getElementById("name").value;
        let json = {
            x: x,
            y: y,
            name: name
        }
        //发送信息
        if (client && client.connected) {
            client.send("/qiuqiu/position", {}, JSON.stringify(json));
            console.log("发送成功");
        } else {
            console.error("WebSocket 连接未建立");
        }
    };

    //发送技能逻辑
    function sendSkill(skillName) {
        let name = document.getElementById("name").value;
        let json = {
            name: name,
            skill: skillName
        }
        //发送信息
        if (client && client.connected) {
            client.send("/game/skill", {}, JSON.stringify(json));
            console.log("技能发送成功");
        } else {
            console.error("WebSocket 连接未建立");
        }
    };
</script>
</html>

